package cn.tedu.st.base.handler;

import cn.tedu.st.base.result.JsonResult;
import cn.tedu.st.base.result.ResultCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 *
 *  实现接口 authenticationEntryPoint		触发场景：未登录用户访问受保护接口
 *  处理未认证用户访问受保护资源的异常（对应HTTP 401或跳转登录页）。
 *  未登录用户直接访问需认证的接口，或Token过期失效。
 *
 *
 *
 */
@Component
@Slf4j
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.debug("进入AnonymousAuthenticationHandler-------");
        log.debug("未登录用户 直接访问需认证 处理器--->抛了一个异常authException={}", authException.getMessage(), authException.getStackTrace());

        // 设置响应内容类型为 JSON，并指定字符编码为 UTF-8
        response.setContentType("application/json;charset=utf-8");

        // 获取响应的输出流，用于写入 JSON 数据
        ServletOutputStream outputStream = response.getOutputStream();


        String jsonString="";



        if (authException instanceof BadCredentialsException){
            //用户名或密码错误
             jsonString = JSON.toJSONString(JsonResult.failure(ResultCode.USERNAME_PASSWORD_ERROR), SerializerFeature.DisableCircularReferenceDetect);
        }else if(authException instanceof InternalAuthenticationServiceException){
            //通常与系统内部的配置、数据访问或依赖服务故障相关，而非用户提供的凭证（如用户名、密码）问题。
            // 用户名不存在
            jsonString = JSON.toJSONString(JsonResult.failure(ResultCode.USERNAME_IS_NULL), SerializerFeature.DisableCircularReferenceDetect);
        }


        else if(authException instanceof DisabledException){
            //账户被禁用异常    账户被禁用,登录失败
            jsonString = JSON.toJSONString(JsonResult.failure(ResultCode.ACCOUNT_DISABLED), SerializerFeature.DisableCircularReferenceDetect);
        }else if (authException instanceof AccountExpiredException){
            //账户过期异常    无权访问,请联系管理员
            jsonString=JSON.toJSONString(JsonResult.failure(ResultCode.ACCOUNT_EXPIRED), SerializerFeature.DisableCircularReferenceDetect);
        }else if (authException instanceof CredentialsExpiredException){
            //密码过期异常   密码过期
            jsonString = JSON.toJSONString(JsonResult.failure(ResultCode.USERNAME_PASSWORD_EXPIRED), SerializerFeature.DisableCircularReferenceDetect);
        }else if (authException instanceof LockedException){
            //账户被锁定      账户被锁定,登录失败
            jsonString = JSON.toJSONString(JsonResult.failure(ResultCode.ACCOUNT_LOCKED), SerializerFeature.DisableCircularReferenceDetect);
        }



        else{
            //匿名用户访问权限不够异常
            jsonString = JSON.toJSONString(JsonResult.failure(ResultCode.UNAUTHORIZED_USER), SerializerFeature.DisableCircularReferenceDetect);
        }

        // 将 JSON 字符串写入响应的输出流，并指定字符编码为 UTF-8
        outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        log.debug("AnonymousAuthenticationHandler执行结束-------");
    }
}
